package com.ash.tx.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.ash.tx.bean.Book;
import com.ash.tx.dao.BookDao;

@Repository
public class BookDaoImpl implements BookDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    
    public Book queryBook(Long id) {
        String sql = "select * from book where id=?";

        Book queryForObject = jdbcTemplate.queryForObject(sql, new RowMapper<Book>() {

            @Override
            public Book mapRow(ResultSet rs, int rowNum) throws SQLException {
                Book book = new Book();
                book.setId(rs.getLong("id"));
                book.setBookName(rs.getString("book_name"));
                book.setPrice(rs.getDouble("price"));
                book.setStockNum(rs.getInt("stock_num"));

                return book;
            }
        }, id);

        return queryForObject;
    }

    public void updateBook(Book book) {
        String sql = "update book set book_name=?,price=?,stock_num=? where id=?";

        jdbcTemplate.update(sql, book.getBookName(), book.getPrice(), book.getStockNum(), book.getId());
    }

}
